﻿#include "sqlite.h"

Sqlite *Sqlite::ptrSql = nullptr;

Sqlite::Sqlite(QObject *parent) : QObject(parent)
{

}

void Sqlite::init()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("user.db");
    if(!db.open())
    {
        qDebug() <<"database not open!";
    }
    qDebug() <<"database open success！";
    QSqlQuery query(db);
    QString sql = "create table if not exists user(name text, pswd text)";//如果存在则不会创建
    if (!query.exec(sql)) {
        qDebug() << "create table: " << query.lastError().text();
        return;
    }
}

bool Sqlite::addUser(User info)
{
    QSqlQuery query(db);
    QString sql =QString("insert into user values ('%1', '%2')")
                    .arg(info.name)
                    .arg(info.pswd);

    if(!query.exec(sql)){
        qDebug() << "insert into user: " << query.lastError().text();
        return false;
    }
    return true;
}

QList<User> Sqlite::getAllUser()
{
    QList<User> list;
    QSqlQuery query(db);
    QString sql = "select * from user";

    query.exec(sql);

    User user;
    while(query.next())
    {
        user.name = query.value(0).toString();
        user.pswd = query.value(1).toString();
        list.push_back(user);
    }
    return list;
}

bool Sqlite::isExist(QString name)
{
    QSqlQuery query(db);
    QString sql =QString("select * from user where name = '%1'").arg(name);
    if(!query.exec(sql)){
        qDebug() << "select * from user name: " << query.lastError().text();
        return false;
    }
    return query.next();
}




